<template>
  <div class="app-container">
    <div class="filter-container">
      <span class="filter-item" style="font-weight: bold">当前地图：</span>
      <el-select v-model="value_map" class="filter-item" placeholder="请选择" @change="currentMap">
        <el-option
          v-for="item in options_map"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model="listQuery.name"
        placeholder="请输入任务名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="任务编号" prop="id" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="定时任务" class-name="status-col" width="120">
        <template slot-scope="{row}">
          <el-tag :type="row.regular | statusFilter">
            {{ row.regular === true ? '启用':'禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="340" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="info" size="mini" @click="handleQuery(row)">
            查看
          </el-button>
          <el-button type="warning" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button size="mini" type="success" @click="handleDistributeRobots(row)">
            机器人分配
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      v-loading="dialogLoading"
      :title="textMap[dialogStatus]"
      :width="dialogWidth"
      :fullscreen="true"
      :visible.sync="dialogFormVisible"
    >
      <el-container>
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="left"
          label-width="80px"
          style="width: 800px; "
        >
          <el-form-item v-if="['query','update'].includes(dialogStatus)" label="任务编号" prop="id">
            <el-input v-model="temp.id" :disabled="['query','update'].includes(dialogStatus)" />
          </el-form-item>
          <el-form-item v-if="['query','create','update'].includes(dialogStatus)" label="任务名称" prop="name">
            <el-input v-model="temp.name" :readonly="['query'].includes(dialogStatus)" placeholder="请输入任务名称" />
          </el-form-item>
          <!--          <el-form-item v-if="['query','create','update'].includes(dialogStatus)" label="任务轨迹" prop="nodes">-->
          <!--            <el-tag-->
          <!--              v-for="(tag,index) in temp.nodes"-->
          <!--              :key="tag.key"-->
          <!--              :closable="['create','update'].includes(dialogStatus)"-->
          <!--              :disable-transitions="false"-->
          <!--              @close="handleClose(index,tag)"-->
          <!--            >-->
          <!--              {{ tag.siteName }}-->
          <!--            </el-tag>-->
          <!--            <el-select-->
          <!--              v-if="['create','update'].includes(dialogStatus) && inputVisible"-->
          <!--              v-model="value"-->
          <!--              class="input-new-tag"-->
          <!--              size="small"-->
          <!--              placeholder="请选择"-->
          <!--              @change="handleInputConfirm(value)"-->
          <!--              @blur="handleVisible(value)"-->
          <!--            >-->
          <!--              <el-option-->
          <!--                v-for="item in options"-->
          <!--                :key="item.id"-->
          <!--                :label="item.label"-->
          <!--                :value="item.value"-->
          <!--                :disabled="item.disabled"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--            <el-button-->
          <!--              v-else-if="['create','update'].includes(dialogStatus)"-->
          <!--              class="button-new-tag"-->
          <!--              size="small"-->
          <!--              @click="showInput"-->
          <!--            >+添加-->
          <!--            </el-button>-->
          <!--          </el-form-item>-->
          <el-form-item v-if="['query','create','update'].includes(dialogStatus)" label="定时任务" prop="regular">
            <el-select
              v-model="temp.regular"
              class="filter-item"
              placeholder="请选择"
              :disabled="['query'].includes(dialogStatus)"
            >
              <el-option v-for="item in statusOptions" :key="item.key" :label="item.text" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="['query','create','update'].includes(dialogStatus) && temp.regular === true"
            label="工作日"
            prop="weekday"
          >
            <el-select
              v-model="temp.weekday"
              class="filter-item"
              placeholder="请选择"
              :disabled="['query'].includes(dialogStatus)"
            >
              <el-option v-for="item in statusOptions" :key="item.key" :label="item.text" :value="item.key" />
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="['query','create','update'].includes(dialogStatus) && temp.regular === true"
            label="执行时间"
            prop="workTime"
          >
            <el-time-picker
              v-model="temp.workTime"
              placeholder="请选择时间"
              type="datetime"
              :readonly="['query'].includes(dialogStatus)"
            />
          </el-form-item>
          <el-form-item v-if="['query','create','update'].includes(dialogStatus)" label="循环执行" prop="loops">
            <el-select
              v-model="temp.loops"
              class="filter-item"
              placeholder="请选择"
              :disabled="['query'].includes(dialogStatus)"
            >
              <el-option v-for="item in loopOptions" :key="item.key" :label="item.text" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="['query','create','update'].includes(dialogStatus) && temp.loops === true"
            label="循环次数"
            prop="loopTimes"
          >
            <el-input-number v-model="temp.loopTimes" :disabled="['query'].includes(dialogStatus)" :min="1" :max="3600" label="循环次数" />
          </el-form-item>
          <el-form-item v-if="['query','create','update'].includes(dialogStatus)" label="自动执行" prop="auto">
            <el-select
              v-model="temp.auto"
              class="filter-item"
              placeholder="请选择"
              :disabled="['query'].includes(dialogStatus)"
            >
              <el-option v-for="item in autoOptions" :key="item.key" :label="item.text" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="['query','create','update'].includes(dialogStatus)" label="任务轨迹" prop="nodes">
            <el-form
              v-if="['create','update'].includes(dialogStatus)"
              :inline="true"
              size="mini"
              class="demo-form-inline"
            >
              <el-form-item label="站点名称">
                <el-select
                  v-model="value"
                  class="input-new-tag"
                  size="small"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.label"
                    :disabled="item.disabled"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="停留时间(秒)">
                <el-input-number v-model="num" :min="1" :max="3600" label="停留时间" />
              </el-form-item>
              <el-button v-if="['create','update'].includes(dialogStatus) && currentRow == null" type="primary" size="mini" @click="addTrack">添加</el-button>
              <el-button v-if="['create','update'].includes(dialogStatus) && currentRow!= null" type="success" size="mini" @click="modifyTrack">修改</el-button>
              <el-button v-if="['create','update'].includes(dialogStatus) && currentRow!= null" size="mini" @click="cancelTrack">取消</el-button>
            </el-form>
            <el-alert
              v-if="['create','update'].includes(dialogStatus)"
              title="通过【选中】站点记录，修改轨迹中站点的信息，修改后请记得【确认】."
              type="success"
              :closable="false"
            />
            <el-table
              ref="singleTable"
              :data="temp.nodes"
              style="height: 100%"
              height="400"
              highlight-current-row
              :row-class-name="tableRowClassName"
              @current-change="handleCurrentChange"
            >
              <el-table-column label="序号" type="index" prop="id" align="center" width="50" />
              <el-table-column
                prop="siteName"
                label="站点名称"
                width="120"
              >
                <template slot-scope="{row}">
                  <span>{{ row.siteName }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="time"
                label="停留时间"
                width="120"
              >
                <template slot-scope="{row}">
                  <span>{{ row.time }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="190" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                  <el-button v-if="['create','update'].includes(dialogStatus)" size="mini" type="danger" @click="deleteTrack(row,$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--            <el-form-->
            <!--              v-if="['create','update'].includes(dialogStatus) && currentRow!=null"-->
            <!--              :inline="true"-->
            <!--              size="mini"-->
            <!--              class="demo-form-inline"-->
            <!--            >-->
            <!--              <el-form-item label="站点名称">-->
            <!--                <el-select-->
            <!--                  v-model="value"-->
            <!--                  class="input-new-tag"-->
            <!--                  size="small"-->
            <!--                  placeholder="请选择"-->
            <!--                >-->
            <!--                  <el-option-->
            <!--                    v-for="item in options"-->
            <!--                    :key="item.id"-->
            <!--                    :label="item.label"-->
            <!--                    :value="value"-->
            <!--                  />-->
            <!--                </el-select>-->
            <!--              </el-form-item>-->
            <!--              <el-form-item label="停留时间(秒)">-->
            <!--                <el-input-number v-model="num" :min="1" :max="3600" label="停留时间" />-->
            <!--              </el-form-item>-->
            <!--              <el-button type="success" size="mini" @click="modifyTrack">修改</el-button>-->
            <!--            </el-form>-->
          </el-form-item>
        </el-form>

        <el-main>
          <div id="viewdiv" />
        </el-main>
        <div class="block">
          <el-slider
            v-model="zoo"
            vertical
            :min="0.1"
            :max="1.9"
            :step="0.1"
            height="200px"
            @change="zoomChange()"
          />
        </div>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button v-if="dialogStatus!='query'" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="机器人分配">
      <div style="text-align: center">
        <el-transfer
          v-model="values.robots"
          style="text-align: left; display: inline-block"
          :render-content="renderFunc"
          :titles="['待分配机器人', '已分配机器人']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
          :data="robots"
          @change="handleChange"
          @mouseover.native="addTitle"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmData(values)">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addTask,
  listRobot,
  listRobotByTaskId,
  listSite,
  listTask,
  modifyTask,
  removeTask,
  saveRobotByTaskId
} from '@/api/map/task-manager'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { validNotNull, validTaskNode } from '@/utils/validate'
import { enableMapInfo, getConfig, listMapAll, mapPreview, queryPoint } from '@/api/map/map'
import pictureMap from '@/utils/pictureMap.js'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'TaskManager',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      currentRow: null,
      num: '3',
      drawer: false,
      direction: 'lft',
      activeName: 'first',
      renderFunc(h, option) {
        return <span> { option.key } - { option.label } </span>
      },
      dialogWidth: '90%',
      zoo: 1,
      values: {
        robots: [],
        taskId: ''
      }, // 已选角色
      robots: [], // 所有角色
      inputVisible: false,
      value: '',
      options: [],
      value_map: '',
      options_map: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      dialogLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        mapId: 0
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ key: true, text: '启用' }, { key: false, text: '禁用' }],
      loopOptions: [{ key: true, text: '是' }, { key: false, text: '否' }],
      autoOptions: [{ key: true, text: '是' }, { key: false, text: '否' }],
      showReviewer: false,
      temp: {
        id: '',
        name: '',
        regular: '',
        loops: '',
        loopTimes: '1',
        auto: '',
        weekday: '',
        workTime: '',
        nodes: [],
        mapId: 0
      },
      dialogFormVisible: false,
      dialogFormVisible1: true,
      dialogStatus: '',
      textMap: {
        query: '查看',
        create: '添加',
        update: '更新'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {},
      downloadLoading: false
    }
  },
  created() {
    this.getListMapAll()
  },
  methods: {
    handleCurrentChange(val) {
      if (val != null) {
        this.value = val.siteName
        this.num = val.time
        this.currentRow = val
        this.disableOptions(this.currentRow.sort)
      }
    },
    disableOptions(idx, sitId) {
      let lastSiteId = ''
      let nowSiteId = ''
      let nextSiteId = ''
      if (this.temp.nodes.length > 0) {
        this.temp.nodes.forEach((item, index) => {
          if (idx > 0 && index === (idx - 1)) {
            lastSiteId = item.siteId
          }
          if (idx >= 0 && index === idx) {
            nowSiteId = item.siteId
          }
          if (idx >= 0 && index === (idx + 1)) {
            nextSiteId = item.siteId
          }
        })
      }
      if (sitId !== undefined) {
        nowSiteId = sitId
        this.options.forEach((item, index) => {
          item.disabled = false
        }
        )
      }
      this.options.forEach((item, index) => {
        item.disabled = false
        if (lastSiteId !== '' && lastSiteId === item.value) {
          item.disabled = true
        }
        if (nowSiteId !== '' && nowSiteId === item.value) {
          item.disabled = true
        }
        if (nextSiteId !== '' && nextSiteId === item.value) {
          item.disabled = true
        }
      })
      if (sitId !== undefined) {
        const op = this.options
        this.options = []
        this.options = op
      }
    },
    disableOptionsForCreated(currSiteId) {
      const fIndex = this.options.findIndex((item, index, arr) => {
        return item.value === currSiteId
      })
      if (fIndex !== -1) {
        this.options.forEach((item, index) => {
          item.disabled = false
          if (fIndex >= 0 && index === fIndex) {
            item.disabled = true
          }
        })
      }
    },
    modifyTrack() {
      console.log('curr', this.currentRow.siteId)

      if (this.value.value === undefined) {
        this.value = {}
        this.value.value = this.currentRow.siteId
        this.value.label = this.currentRow.siteName
      }
      console.log('==========================2', this.value.value)
      console.log('==========================3', this.num)
      console.log('==========================4', this.value.label)
      console.log('==========================5', this.value)
      let nowIndex = ''
      let nowSiteId = ''
      this.temp.nodes.forEach((item, index) => {
        if (index === this.currentRow.sort) {
          item.siteId = this.value.value
          item.siteName = this.value.label
          item.time = this.num
          nowIndex = index
          nowSiteId = this.value.value
        }
      })
      console.log('==========================1', this.currentRow.sort)
      this.disableOptions(nowIndex, nowSiteId)
      console.log('==========================1', this.currentRow.sort)
      this.$message({
        message: '第' + (this.currentRow.sort + 1) + '条记录已更改,最终确定后生效',
        type: 'success'
      })
    },
    cancelTrack() {
      this.$refs.singleTable.setCurrentRow(null)
      this.currentRow = null
      this.value = ''
      if (this.options.length > 0 && this.temp.nodes.length > 0) {
        this.disableOptionsForCreated(this.temp.nodes[this.temp.nodes.length - 1].siteId)
      }
    },
    deleteTrack(item, index) {
      this.$refs.singleTable.setCurrentRow(null)
      this.temp.nodes.splice(index, 1)
    },
    addTrack() {
      if (this.value.value == null) {
        this.$message({
          showClose: true,
          message: '请选择有效的站点',
          type: 'warning'
        })
        return
      }
      if (this.temp.nodes.length > 0 && (this.value.value === this.temp.nodes[this.temp.nodes.length - 1].siteId)) {
        this.$message({
          showClose: true,
          message: '轨迹上不可以连续到达同一站点',
          type: 'warning'
        })
        return
      }
      const table = {
        siteId: this.value.value,
        siteName: this.value.label,
        time: this.num
      }
      this.temp.nodes.push(table)
      this.temp.nodes.forEach((item, index) => {
        item.sort = index
      })
      if (this.options.length > 0 && this.temp.nodes.length > 0) {
        this.disableOptionsForCreated(this.temp.nodes[this.temp.nodes.length - 1].siteId)
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    handleClick(tab, event) {
    },
    addTitle(e) {
      const target_el = e.target
      if (target_el.title) return
      target_el.title = target_el.innerText
    },
    getRobotList: function() {
      const robot = []
      const param = {
        mapId: this.listQuery.mapId,
        active: false
      }
      listRobot(param).then(response => {
        const { data } = response
        const result = data || []
        result.forEach(item => {
          robot.push({
            key: item.id,
            label: item.name + '-' + item.mac
          })
        })
      })
      this.robots = robot
    },
    init: function() {
      this.values = {
        robots: [],
        taskId: ''
      } // 已选角色
      this.inputVisible = false
      this.tableKey = 0
      this.list = null
      this.total = 0
      this.listLoading = true
      this.listQuery = {
        pageNum: 1,
        pageSize: 10,
        name: '',
        mapId: 0
      }
      this.importanceOptions = [1, 2, 3]
      this.temp = {
        id: '',
        name: '',
        regular: '',
        loops: '',
        loopTimes: '1',
        auto: '',
        weekday: '',
        workTime: '',
        nodes: [],
        mapId: 0
      }
      this.robots = [] // 所有角色
      this.value = ''
      this.options = []
      this.dialogFormVisible = false
      this.dialogFormVisible1 = true
      this.dialogStatus = ''
      this.dialogPvVisible = false
      this.pvData = []
      this.rules = {}
      this.downloadLoading = false
    },
    getListMapAll: function() {
      listMapAll().then(response => {
        response.data.forEach((item) => {
          const name = (!item.name && typeof (item.name) !== 'undefined' && item.name !== 0) || item.name === '' ? '未命名' : item.name
          const option = {
            value: item.id,
            // eslint-disable-next-line no-undef,eqeqeq
            label: item.id + '--' + name
          }
          this.options_map.push(option)
          if (item.enabled === true) {
            this.value_map = item.id + '--' + name
            this.listQuery.mapId = item.id
          }
        })
        this.getList()
        this.getRobotList()
      })
    },
    currentMap: function(id) {
      const param = {
        id: id
      }
      enableMapInfo(param).then(response => {
        this.init()
        this.listQuery.mapId = param.id
        this.getList()
        this.getRobotList()
        this.pictureMapId = ''
        this.pictureMapId = undefined
        this.$message({
          type: 'success',
          message: '切换成功！'
        })
      })
    },
    handleChange(value, direction, movedKeys) {
    },
    confirmData(values) {
      this.listLoading = true
      saveRobotByTaskId({ 'robotIds': values.robots, 'taskId': values.taskId }).then(() => {
        this.listLoading = false
        this.$notify({
          title: '成功',
          message: '机器人分配',
          type: 'success',
          duration: 2000
        })
        this.dialogPvVisible = false
      })
    },
    // handleVisible(value) {
    //   if (value) {
    //     if (this.options && this.options.length > 0) {
    //       console.log('handleVisible', value)
    //       this.options.forEach(item => {
    //         if (value.id === item.id) {
    //           item.disabled = true
    //         } else {
    //           item.disabled = false
    //         }
    //       })
    //     }
    //   }
    // },
    handleInputConfirm(value) {
      // if (value) {
      //   const ve = {
      //     key: new Date().getTime().toLocaleString(),
      //     id: value.id,
      //     siteId: value.id,
      //     siteName: value.name
      //   }
      //   if (this.options && this.options.length > 0) {
      //     this.options.forEach(item => {
      //       if (value.id === item.id) {
      //         item.disabled = true
      //       } else {
      //         item.disabled = false
      //       }
      //     })
      //   }
      //   console.log('options', this.options)
      //   this.temp.nodes.push(ve)
      // }
      // this.value = ''
    },
    listSite() {
      listSite({ mapId: this.listQuery.mapId }).then(response => {
        const { data } = response
        this.options = this.buildOptions(data)
        if (this.options.length > 0 && this.temp.nodes.length > 0) {
          this.disableOptionsForCreated(this.temp.nodes[this.temp.nodes.length - 1].siteId)
        }
      })
    },
    // 组装options
    buildOptions(data) {
      const result = []
      if (data.length > 0) {
        data.forEach(item => {
          result.push({
            label: item.name,
            value: item.id,
            time: item.time
          })
        })
      }
      return result
    },
    handleDistributeRobots(row) {
      this.values = {
        robots: [],
        taskId: ''
      }
      this.robots = []
      this.listLoading = true
      this.getRobotList()
      // 获取已选中机器人
      listRobotByTaskId({ taskId: row.id }).then(response => {
        const { data } = response
        const result = data || []
        const robots = []
        result.forEach(item => {
          robots.push(item.id)
        })
        this.values.robots = robots
        this.values = {
          robots: robots,
          taskId: row.id
        }
        this.listLoading = false
      })
      this.dialogStatus = 'distribute'
      this.dialogPvVisible = true
    },
    getList() {
      this.listLoading = true
      listTask(this.listQuery).then(response => {
        console.log('data', response.data.list)
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        name: '',
        regular: '',
        weekday: '',
        workTime: '',
        nodes: []
      }
    },
    handleCreate() {
      this.rules = {
        name: [{ required: true, trigger: ['blur', 'change'], message: '任务名称不能为空' }],
        nodes: [{ required: true, trigger: ['blur', 'change'], validator: validTaskNode }],
        regular: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '定时任务' }],
        loops: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '循环执行' }],
        auto: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '是否自动' }],
        loopTimes: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '循环次数' }],
        weekday: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '工作日' }],
        workTime: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '执行时间' }]
      }
      this.resetTemp()
      if (this.currentRow != null) {
        this.$refs.singleTable.setCurrentRow(null)
        this.currentRow = null
      }
      this.value = ''
      this.num = 3
      if (this.pictureMapId === undefined || this.pictureMapId === '') {
        this.getMap()
      }
      this.dialogStatus = 'create'
      this.listSite()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      if (this.pictureMapId === undefined || this.pictureMapId === '') {
        this.getMap()
      }
      this.rules = {
        name: [{ required: true, trigger: ['blur', 'change'], message: '任务名称不能为空' }],
        nodes: [{ required: true, trigger: ['blur', 'change'], validator: validTaskNode }],
        regular: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '定时任务' }],
        loops: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '循环执行' }],
        auto: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '是否自动' }],
        loopTimes: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '循环次数' }],
        weekday: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '工作日' }],
        workTime: [{ required: true, trigger: ['blur', 'change'], validator: validNotNull, name: '执行时间' }]
      }
      if (this.currentRow != null) {
        this.$refs.singleTable.setCurrentRow(null)
        this.currentRow = null
      }
      this.value = ''
      this.num = 3
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.listSite()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.dialogLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.mapId = this.listQuery.mapId
          addTask(this.temp).then(response => {
            const { data } = response
            this.temp.id = data
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 3000
            })
          })
        }
        this.dialogLoading = false
      })
    },
    updateData() {
      this.dialogLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.mapId = this.listQuery.mapId
          modifyTask(this.temp).then(response => {
            const { data } = response
            this.temp.id = data
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 3000
            })
          })
        }
        this.dialogLoading = false
      })
    },
    handleQuery(row) {
      if (this.pictureMapId === undefined || this.pictureMapId === '') {
        this.getMap()
      }
      this.rules = {}
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'query'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, index) {
      this.listLoading = true
      removeTask({ id: row.id }).then(() => {
        this.dialogFormVisible = false
        this.listLoading = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    getPoints: function() {
      var that = this
      queryPoint({
        'mapId': that.pictureMapId
      }).then(response => {
        this.map.removePoints()
        this.map.addPOIPoints(response.data)
      })
    },
    zoomChange: function() {
      this.map.zoom(this.zoo)
    },
    getMap: function() {
      const that = this
      getConfig().then(response => {
        if (response.data.mapId == null) {
          this.$alert('请选择有效的地图', '暂无地图', {
            confirmButtonText: '确定'
          })
        }
        const originX = response.data.originX
        const originY = response.data.originY
        that.pictureMapId = response.data.mapId
        // eslint-disable-next-line new-cap
        that.map = new pictureMap({
          viewId: 'viewdiv', // 地图ID（必填参数）
          mapImg: mapPreview(), // 地图底图（可选参数，可无底图）
          markerImg: '<i class="el-icon-location" style="color: #1890ff"></i>', // POI点的图标（可选参数）
          markerStart: '<i class="el-icon-location" style="color: mediumseagreen"></i>', // POI点的图标（可选参数）
          isEditor: false, // 是否开启编辑功能
          originX: originX,
          originY: originY,
          pictureMapId: that.pictureMapId,
          resolution: response.data.resolution,
          width: response.data.with,
          height: response.data.height,
          isRealSize: false,
          uploadFun: function(data) {
            that.form = data
            that.dialogVisible = true
            that.isEditOrAdd = 2
          }, // 上传POI点,自处理
          clickFun: function(data) {
          }// 点击POI点所触发的事件,data数据格式{dataId:dateId,top:top,left:left,attributes:attributes};（可选参数，可以不上传）
        }, that)
        that.zoom = this.map.getScale()
        that.getPoints()
      })
    }
  }
}
</script>
<style>
  .el-main {
    width: 564px;
    height: 351px;
    border: 1px solid black;
    padding: 0;
    margin-left: 64px;
  }

  #viewdiv {
    margin: 0;
    padding: 0;
    /*height: calc(100vh - 190px);*/
    height: 350px;
    position: absolute;
    overflow: hidden;
    width: 528px;
  }

  .el-tag {
    margin-left: 1px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    height: 32px;
    margin-left: 1px;
    padding-top: 0;
    padding-bottom: 0;
  }
</style>
